@{
    ViewData["Title"] = "修改设备点检保养项目";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>@ViewData["Title"]</title>
    <!-- 引入layui CSS -->
    <link rel="stylesheet" href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css">
    
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #f2f2f2;
        }
        .form-container {
            padding: 20px;
            background-color: #fff;
            height: 100vh;
            overflow-y: auto;
        }
        .form-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #1E9FFF;
            padding-bottom: 10px;
        }
        .layui-form-label {
            width: 120px;
        }
        .layui-input-block {
            margin-left: 150px;
        }
        .required-star {
            color: red;
            margin-right: 3px;
        }
        .button-area {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e6e6e6;
            text-align: center;
        }
        .layui-textarea {
            min-height: 100px;
        }
        .loading-shade {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            z-index: 9999;
            display: none;
        }
        .loading-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }
    </style>
</head>
<body>

<div class="loading-shade" id="loadingShade">
    <div class="loading-content">
        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate"></i>
        <p>正在加载数据...</p>
    </div>
</div>

<div class="form-container">
    <div class="form-title">
        <i class="layui-icon layui-icon-edit"></i> 修改设备点检保养项目
    </div>

    <form class="layui-form" lay-filter="editForm" id="editForm">
        <!-- 隐藏字段保存ID -->
        <input type="hidden" name="Id" id="hiddenId">

        <!-- 项目编码 -->
        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="required-star">*</span>项目编码
            </label>
            <div class="layui-input-block">
                <input type="text" name="ProjectCode" lay-verify="required" placeholder="请输入项目编码" autocomplete="off" class="layui-input" id="projectCodeInput">
            </div>
        </div>

        <!-- 项目名称 -->
        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="required-star">*</span>项目名称
            </label>
            <div class="layui-input-block">
                <input type="text" name="ProjectName" lay-verify="required" placeholder="请输入项目名称" autocomplete="off" class="layui-input">
            </div>
        </div>

        <!-- 项目类型 -->
        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="required-star">*</span>项目类型
            </label>
            <div class="layui-input-block">
                <select name="ProjectType" lay-verify="required" lay-filter="projectTypeSelect">
                    <option value="">请选择项目类型</option>
                    <option value="设备点检">设备点检</option>
                    <option value="设备保养">设备保养</option>
                </select>
            </div>
        </div>

        <!-- 项目内容 -->
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">
                <span class="required-star">*</span>项目内容
            </label>
            <div class="layui-input-block">
                <textarea name="ProjectContent" lay-verify="required" placeholder="请输入项目内容" class="layui-textarea"></textarea>
            </div>
        </div>

        <!-- 标准 -->
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">标准</label>
            <div class="layui-input-block">
                <textarea name="Standard" placeholder="请输入标准（可选）" class="layui-textarea"></textarea>
            </div>
        </div>

        <!-- 是否启用 -->
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input type="radio" name="IsEnabled" value="true" title="是">
                <input type="radio" name="IsEnabled" value="false" title="否">
            </div>
        </div>

        <!-- 备注 -->
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="Remark" placeholder="请输入备注（可选）" class="layui-textarea"></textarea>
            </div>
        </div>

        <!-- 按钮区域 -->
        <div class="button-area">
            <button type="submit" class="layui-btn" lay-submit lay-filter="submitForm">
                <i class="layui-icon layui-icon-ok"></i> 确定
            </button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">
                <i class="layui-icon layui-icon-close"></i> 取消
            </button>
        </div>
    </form>
</div>

<!-- 引入jQuery -->
<script src="~/libs/jquery/jquery.js"></script>
<!-- 引入layui JS -->
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<script>
// 等待页面DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    console.log('Edit页面DOM加载完成');
    
    // 检查layui是否正确加载
    if (typeof layui === 'undefined') {
        console.error('layui未正确加载！');
        alert('layui框架加载失败，请检查网络连接！');
        return;
    }
    
    console.log('layui已加载，版本:', layui.version);
    
    layui.use(['form', 'layer'], function(){
        var form = layui.form;
        var layer = layui.layer;
        
        console.log('layui模块加载完成');
        
        // 获取URL参数中的ID
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }
        
        var itemId = getUrlParameter('id');
        console.log('获取到的ID:', itemId);
        
        if (!itemId) {
            layer.alert('参数错误：缺少ID参数', {icon: 2}, function() {
                // 返回列表页
                goBackToList();
            });
            return;
        }
        
        // 加载数据
        loadData(itemId);
        
        // 加载数据函数
        function loadData(id) {
            console.log('加载数据:', id);
            // 显示加载遮罩
            $('#loadingShade').show();
            
            $.ajax({
                url: '@Url.Action("Get", "Maintenanceplan", new { area = "ProductionSystem" })/' + id,
                type: 'GET',
                success: function(result) {
                    $('#loadingShade').hide();
                    console.log('数据加载结果:', result);
                    
                    if (result.success && result.data) {
                        var data = result.data;
                        
                        // 填充表单数据
                        $('#hiddenId').val(data.id);
                        $('input[name="ProjectCode"]').val(data.projectCode);
                        $('input[name="ProjectName"]').val(data.projectName);
                        $('select[name="ProjectType"]').val(data.projectType);
                        $('textarea[name="ProjectContent"]').val(data.projectContent);
                        $('textarea[name="Standard"]').val(data.standard || '');
                        $('input[name="IsEnabled"][value="' + data.isEnabled + '"]').prop('checked', true);
                        $('textarea[name="Remark"]').val(data.remark || '');
                        
                        // 重新渲染表单
                        form.render();
                        
                        console.log('数据填充完成');
                    } else {
                        layer.alert('数据加载失败: ' + (result.message || '未知错误'), {icon: 2}, function() {
                            goBackToList();
                        });
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingShade').hide();
                    console.error('数据加载失败:', error);
                    layer.alert('网络错误，数据加载失败', {icon: 2}, function() {
                        goBackToList();
                    });
                }
            });
        }
        
        // 监听表单提交
        form.on('submit(submitForm)', function(data){
            console.log('表单提交:', data.field);
            
            var submitData = data.field;
            submitData.Id = parseInt(submitData.Id);
            submitData.IsEnabled = submitData.IsEnabled === 'true';
            
            // 显示加载层
            var loadingIndex = layer.load(1, {
                shade: [0.1, '#fff']
            });
            
            $.ajax({
                url: '@Url.Action("Update", "Maintenanceplan", new { area = "ProductionSystem" })',
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(submitData),
                success: function(result) {
                    layer.close(loadingIndex);
                    console.log('更新结果:', result);
                    
                    if (result.success) {
                        layer.msg(result.message, {icon: 1}, function() {
                            // 使用全局页面导航工具返回并刷新列表
                            if (window.PageNavigator) {
                                window.PageNavigator.onSuccess('更新成功', function() {
                                    // 刷新父页面表格
                                    if (parent && parent.refreshMaintenanceplanTable) {
                                        parent.refreshMaintenanceplanTable();
                                    }
                                });
                            } else {
                                // 降级处理
                                if (parent && parent.refreshMaintenanceplanTable) {
                                    parent.refreshMaintenanceplanTable();
                                }
                                goBackToList();
                            }
                        });
                    } else {
                        layer.msg(result.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loadingIndex);
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                }
            });
            
            return false; // 阻止表单跳转
        });
        
        // 取消按钮事件
        $('#cancelBtn').on('click', function() {
            console.log('点击取消按钮');
            layer.confirm('确定要取消吗？未保存的数据将丢失', {
                btn: ['确定', '继续编辑'],
                title: '取消确认'
            }, function(index) {
                layer.close(index);
                goBackToList();
            });
        });
        
        // 返回列表页面的通用方法
        function goBackToList() {
            console.log('返回列表页面');
            // 使用全局页面导航工具返回
            if (window.PageNavigator) {
                window.PageNavigator.goBack();
            } else {
                // 降级处理
                if (parent && parent.loadPage) {
                    parent.loadPage('@Url.Action("Index", "Maintenanceplan", new { area = "ProductionSystem" })');
                } else {
                    history.back();
                }
            }
        }
        
        console.log('Edit页面事件绑定完成');
    });
});
</script>

</body>
</html> 